import dayjs from 'dayjs';

export default {
	data() {
		return {
			loading: false,
			autoLoad: true,
			query: {
				page: 1,
				size: 20
			},
			loadFunc: () => {
			},
			tableAttrs: this.$utils.tableAttrs({
				size: 'medium',
				rowKey: true,
				border: true,
				stripe: true,
				columns: [],
				toolbarConfig: {
					custom: true,
					zoom: true,
					slots: {
						buttons: 'buttons'
					}
				}
			}),
			table: {
				rows: [],
				count: 0
			}
		}
	},
	created() {
		this.autoLoad && this.getTableData();
	},
	computed: {
		pageLength() {
			let total = Math.ceil(this.table.count / this.query.size)
			return isNaN(total) ? 1 : total
		}
	},
	methods: {
		getTableData() {
			this.loading = true;
			let result = this.loadFunc();
			if (!result) {
				this.loading = false;
			}
			result.then(res => {
				this.$utils.responseHandler(res, true, true).then(({data}) => {
					if (this.dataCallback && this.dataCallback instanceof Function) {
						this.dataCallback(data)
						return;
					}
					this.table.rows = this._getData(data);
					this.table.count = data.count || 0;
				})
			}).finally(() => this.loading = false)
		},
		onRefresh() {
			this.onSearch();
		},
		onSearch() {
			this.query.page = 1;
			this.getTableData();
		},
		_getData(data) {
			if (!data) {
				return []
			} else if (data.rows) {
				return data.rows
			} else if (data.rows === null) {
				return []
			}
			return data
		},
		dateFormatter(date) {
			if (date) {
				return dayjs(date).format('YYYY-MM-DD HH:mm:ss')
			}
			return date;
		},
		onPageChange({type, currentPage, pageSize}) {
			this.query.page = currentPage;
			this.query.size = pageSize;
			this.getTableData();
		},
		edit(row) {
			this.$refs.dialog.edit(row);
		},
	}
}